package cn.touna.jss.common.mq;

import cn.touna.risk.api.utils.IntfTypeUtil;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author:wuwc
 * @Description:
 * @Date:2018/3/5 20:45
 */
public class KafkaUtils {

    /**
     * 组装kafka 信息
     *
     * @param request
     * @param response
     * @return
     * @throws UnknownHostException
     */
    public static String assembleKafkaMsg(CreditQueryRequest request, Response response) {
        JSONObject jb = new JSONObject();
        jb.put("dataSource", "001");
        jb.put("dataType", IntfTypeUtil.splitIntfType(request.getMethod())[0]);
        jb.put("bizType", IntfTypeUtil.splitIntfType(request.getMethod())[1]);
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String currentIpAddress = address.getHostAddress();
        jb.put("userIp", currentIpAddress);
        jb.put("collectTime", System.currentTimeMillis());
        jb.put("sessionId", TracerContextUtil.getTraceId());
        jb.put("crNo", request.getCrNo());
        JSONObject timeline = new JSONObject();
        timeline.put("timeApiCallSend", request.getQueryTime());
        timeline.put("timeToProfileEngine", System.currentTimeMillis());
        // 设置返回结果
        JSONObject data = new JSONObject();
        data.put("flowNo", response.getFlowNo());
        data.put("code", response.getCode());
        data.put("msg", response.getMsg() == null ? "" : response.getMsg());
        data = setIdCardPhone(request, data);
        if (response.getData() == null) {
            data.put("response", "");
        } else {
            data.put("response", response.getData());
        }
        // 设置请求参数
        data.put("request", request.getParams());
        jb.put("timeline", timeline);
        jb.put("data", data);
        return jb.toString();
    }

    public static String assmbleQueryResult(CreditQueryRequest request, Response response) {
        JSONObject result = new JSONObject();
        result.put("request", request);
        result.put("response", response);
        return result.toJSONString();
    }


    private static JSONObject setIdCardPhone(CreditQueryRequest request, JSONObject data) {
        JSONObject params = request.getParams();
        String id_card = params.get("idCard") == null ? request.getIdCard() : (String) params.get("idCard");
        String phone = params.get("mobile") == null ? request.getMobile() : (String) params.get("mobile");
        data.put("id_card", id_card == null ? "" : id_card);
        data.put("phone_no", phone == null ? "" : phone);
        return data;
    }

}
